String.prototype.format = function() {
    var formatted = this;
    for( var arg in arguments ) {
        formatted = formatted.replace("{" + arg + "}", arguments[arg]);
    }
    return formatted;
};

var PRE_CONTENT_LIST = [];

//// function start

function show_sequence_diagram(pos) {
    var data = PRE_CONTENT_LIST[pos];
    // console.log('show_sequence_diagram', pos, data);
    var diagram = Diagram.parse(data);
    $("#__diagram_result_container_"+pos).html('');
    diagram.drawSVG("__diagram_result_container_"+pos, {theme: 'simple'});
}

function show_flowchart_diagram(pos) {
    var data = PRE_CONTENT_LIST[pos];
    // console.log('show_flowchart_diagram', pos, data);
    var diagram = flowchart.parse(data);
    $("#__diagram_result_container_"+pos).html('');
    diagram.drawSVG("__diagram_result_container_"+pos);
}

function show_mermaid_diagram(pos) {
    var data = PRE_CONTENT_LIST[pos];
    console.log('show_mermaid_diagram', pos, data);

    var element = document.querySelector("#__diagram_result_container_"+pos);
    
    var insertSvg = function(svgCode, bindFunctions){
        element.innerHTML = svgCode;
        console.log('show_mermaid_diagram result:', svgCode)
    };

    var graphDefinition = data;
    var graph = mermaidAPI.render("__diagram_mermaid_result_"+pos, graphDefinition, insertSvg); // 第一个参数是生成的svg的id
}


function dowbload_current_fullcreen_svg() {
    
    var svg = $('#__diagram_fullscreen_svg_container svg')[0];
    var width = parseInt(svg.width.baseVal.value);
    var height = parseInt(svg.height.baseVal.value);
    var xml = '<?xml version="1.0" encoding="utf-8" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"><svg xmlns="http://www.w3.org/2000/svg" width="' + width + '" height="' + height + '" xmlns:xlink="http://www.w3.org/1999/xlink">' + svg.innerHTML + '</svg>';

    var a = document.createElement("a");
    a.download = "diagram.svg";
    a.href = "data:image/svg+xml," + encodeURIComponent(xml);
    a.click();
    
}

//// function end


$("pre").each(function(index,obj){
    var $pre = $(this);
    PRE_CONTENT_LIST.push($pre.text());
    // 添加div
    if ($('#__diagram_result_container_{0}'.format(index)).length == 0) {
        $pre.after("<div class='__diagram_result_container' id='__diagram_result_container_{0}' style='display:block; max-width:100%;overflow-x:auto;'></div>".format(index));
    }
    console.log('try render ', index);
    try{
        show_sequence_diagram(index);
    } catch (err) {
        console.log('show_sequence_diagram error: ', index, err);
        try{
            show_flowchart_diagram(index);
        } catch (err) {
            console.log('show_flowchart_diagram error: ', index, err);
            try {
                show_mermaid_diagram(index);
            } catch(err) {
                console.log('show_mermaid_diagram error: ', index, err);
            }
        }
    }

    var children = $("#__diagram_result_container_{0} svg".format(index)).children();
    // 如果除了desc和defs，没有其他的tag，则将图删掉
    var has_other_tag = false;
    for (var i=0; i<children.length;++i) {
        if (children[i].tagName != 'desc' && children[i].tagName != 'defs') {
            has_other_tag = true;
        }
    }
    console.log(has_other_tag, children);
    if (!has_other_tag) {
        $("#__diagram_result_container_"+index).html('');
    }
    
});

//// 全屏
if ($('#__diagram_fullscreen_container').length == 0) {
    $('body').append("<div id='__diagram_fullscreen_container' class='__diagram_fullscreen_container_hide'><div id='__diagram_fullscreen_op_container'><button id='__diagram_fullscreen_download_btn'>Download</button><button id='__diagram_fullscreen_close_btn'>Close</button></div><div id='__diagram_fullscreen_svg_container'></div></div>");
    $('div .__diagram_result_container').dblclick(function(eve){
        console.log('dblclick');
        var svgCode = $(eve.currentTarget).html();
        $('#__diagram_fullscreen_container').removeClass('__diagram_fullscreen_container_hide')
                                            .addClass('__diagram_fullscreen_container_show');
        $('#__diagram_fullscreen_svg_container').html(svgCode);
    });
    $('#__diagram_fullscreen_close_btn').click(function(eve){
        $('#__diagram_fullscreen_container').removeClass('__diagram_fullscreen_container_show')
        .addClass('__diagram_fullscreen_container_hide');
    });
    $('#__diagram_fullscreen_download_btn').click(function(eve){
        dowbload_current_fullcreen_svg();
    });
}